<?php
/**
 * (ajax)
 */
namespace App\Admin\Ajax\Operation;

use App\Models\Basics\AmazonCountry;
use App\Models\Basics\ExchangeRate;
use App\Models\Basics\SysICountry;
use App\Models\Basics\Transport;
use App\Models\Operation\ProfitSku;
use App\Models\Operation\ProfitTry;
use Encore\Admin\Facades\Admin;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
class ProfitAjax {

    /**
     * 产品毛利率（calculate:profit-sku）
     * @return \Illuminate\Http\JsonResponse
     */
    public function calculateProfitSku(){
        try{
            Artisan::call('calculate:profit-sku');
            return response()->json(['status' => true, 'message' => '操作成功！']);
        }catch (\Exception $e){
            report($e);
            return response()->json(['status' => false, 'message' => '系统异常！']);
        }
    }

    /**
     * 试算产品毛利率（calculate:profit-try）
     * @return \Illuminate\Http\JsonResponse
     */
    public function calculateProfitTry(){
        try{
            Artisan::call('calculate:profit-try');
            return response()->json(['status' => true, 'message' => '操作成功！']);
        }catch (\Exception $e){
            report($e);
            return response()->json(['status' => false, 'message' => '系统异常！']);
        }
    }

    /**
     * 添加试算产品
     * @param $param
     * @return \Illuminate\Http\JsonResponse
     */
    public function addProfitTry($param){
        try{
            $countryId = $param['country_id'];
            $areaId = SysICountry::getAreaIdByCountryId($countryId);
            if(!$areaId){
                return response()->json(['status' => false, 'message' => '国家对应站点不存在！']);
            }
            $p = ProfitTry::query()->where('country_id',$countryId)->where('sku_cn',$param['sku_cn'])->first();
            if($p){
                return response()->json(['status' => false, 'message' => '国家+SKU重复添加！']);
            }
            $currencyCode = AmazonCountry::getCurrencyCodeByCountryId($countryId);
            if(!$currencyCode){
                return response()->json(['status' => false, 'message' => '国家对应币种不存在！']);
            }
            DB::beginTransaction();
            $param['rate_odds'] = ExchangeRate::getRateOddsToRMB($currencyCode,time());
            $param['vat'] = $param['vat'] ?: 0;
            $param['seller_id'] = Admin::user()->id;
            $transportFee = Transport::getTransportFee($areaId);
            $airFee = $transportFee->air_fee ?? 0;
            $seaFee = $transportFee->sea_fee ?? 0;
            $_param = $param;
            //空运
            $param['transport'] = 2;
            $param['head_cost'] = round($param['weight'] * $airFee / $param['rate_odds'],3);
            $tpl = round($param['tpl_rmb'] / $param['rate_odds'],3);
            $param['cost'] = ProfitSku::getCost($tpl,$param['sale_price'],$param['head_cost'],$param['fba_fee'],$param['commission'],$param['return'],$param['vat']);
            $param['profit'] = round($param['sale_price'] - $param['cost'],3);
            $param['profit_rate'] = round($param['profit'] / $param['sale_price'] ,3);
            $flag1 = ProfitTry::query()->create($param);
            if(!$flag1){
                DB::rollBack();
                return response()->json(['status' => false, 'message' => '操作失败！']);
            }
            //海运
            $_param['transport'] = 1;
            $_param['head_cost'] = round($_param['weight'] * $seaFee / $_param['rate_odds'],3);
            $_tpl = round($_param['tpl_rmb'] / $_param['rate_odds'],3);
            $_param['cost'] = ProfitSku::getCost($_tpl,$_param['sale_price'],$_param['head_cost'],$_param['fba_fee'],$_param['commission'],$_param['return'],$_param['vat']);
            $_param['profit'] = round($_param['sale_price'] - $_param['cost'],3);
            $_param['profit_rate'] = round($_param['profit'] / $_param['sale_price'] ,3);
            $flag2 = ProfitTry::query()->create($_param);
            if(!$flag2){
                DB::rollBack();
                return response()->json(['status' => false, 'message' => '操作失败！']);
            }
            DB::commit();
            return response()->json(['status' => true, 'message' => '操作成功！']);
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => '系统异常！']);
        }
    }
}
